import React, { VFC, useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { Menu } from "antd";
import { getProjectPhaseMenu} from '@services/index';

import "./style.css";

const { SubMenu } = Menu;
const MenuItem = Menu.Item;

const Menus: VFC = () => {
  const history = useHistory();
  const pathName = history.location.pathname;
  const firstGroupMenu = {
      id:2,
      name: '小组管理',
      phaseTemplateList: [
          {id:2,name:'小组管理 ',routePath: 'group'},
          {id:3,name:'组员管理',routePath: 'team'},
      ]
  };
  const lastGroupMenu = {id:1,name:'排行榜',routePath:'ranking'};
  const [menuList, setMenuList] = useState<any>([]);
  const [openKey, setOpenKey] = useState<any>([]);
  const [selectedKeys, setSelectedKeys] = useState<any>([]);

  useEffect(() => {    
    getMenuList();
  }, []);

  useEffect(() => {
    setInitData(pathName)
  }, [pathName]);
  
  // 切换页面
  const handleClick = (e: any) => {
    if(e.routePath){
      history.push({ pathname: e.routePath, state: e})
      setInitData(`/${e.routePath}`)
    }
  };

  const getMenuList = async () => {
    const { data, status } = await getProjectPhaseMenu({
      projectId: JSON.parse(sessionStorage.userInfo).projectId,
      clientType: 2 	// 客户端 2 教师 3 学生
    })
    if(status === '0'){
      const _data = data.project;
      const newPhaseList = _data.phaseList.filter((e:any) => {
        if(e.phaseTemplateList && e.phaseTemplateList.length > 0) return e;
      });
      _data.phaseList = newPhaseList;
      setMenuList([firstGroupMenu, _data, lastGroupMenu])
    }
  }

  // 触发 menu
  const onOpenChange = (openKeys: React.Key[]):void => setOpenKey(openKeys);

  //  设置OpenKey和SelectedKeys
  const setInitData = (routePath:string) => {
    const initData: any = initKey(menuList, routePath);
    if(initData){
        setOpenKey(initData.openKey);
        setSelectedKeys([initData.name]);
    }else{
        const getPath = (list:any):any => {
            if(list.phaseTemplateList&&list.phaseTemplateList?.length>0){
                return getPath(list.phaseTemplateList[0])
            }else{
                return list.routePath
            }
        }
        const routePath = getPath(menuList[0])
        history.push(routePath);
        setInitData(`/${routePath}`)
    }
  }
  // 递归选取上层数据 openKey表示 当前 menu 上层 name
  const initKey = (data: any, pathKey: string): object | null => {
    const list: any[] = [];
    const getList = (data: any): void => {
      data.map((item: any) => {
        if (item.phaseTemplateList && item.phaseTemplateList?.length) {
          const phaseTemplateList = item.phaseTemplateList?.map((subItem: any) => ({
            ...subItem,
            openKey: item.openKey ? [...item.openKey, item.name] : [item.name],
          }));
          getList(phaseTemplateList); // 递归调用
        } else {
          let newItem = { ...item };
          if (!Object.prototype.hasOwnProperty.call(item, "openKey")) {
            newItem = { ...item, openKey: item.name };
          }
          list.push(newItem);
        }
      });
    };
    getList(data);
    const filtered = list.find((item) => `/${item.routePath}` === pathKey);
    return filtered;
  };

  const renderSubMenu = (el: any) => (
    <SubMenu key={el.name} title={el.name}>
      {el!.phaseTemplateList?.map((_el: any) => (
        <MenuItem key={_el.name} onClick={() => handleClick(_el)}>
          {_el.name}
        </MenuItem>
      ))}
    </SubMenu>
  );

  const renderMenuItem = (el: any) => (
    <MenuItem key={el.name} onClick={() => handleClick(el)}>
      {el.name}
    </MenuItem>
  );

  return (
    <Menu
      className="box-menus"
      selectedKeys={selectedKeys}
      openKeys={openKey}
      mode="inline"
      theme="dark"
      onOpenChange={onOpenChange}
    >
      {menuList.map((item: any) => (
        <SubMenu key={item.name} title={item.name}>
          {item?.phaseTemplateList?.map((el: any) =>
            el!.phaseTemplateList && el.phaseTemplateList?.length > 0
              ? renderSubMenu(el)
              : renderMenuItem(el)
          )}
        </SubMenu>
      ))}
    </Menu>
  );
};
export default Menus;
